import tornado.web
from tornado.websocket import WebSocketHandler
from db import db
from utils.Myredis import r
import time,json
from flask import Blueprint
from flask_restful import Api
websocket_blue=Blueprint("vip_order",__name__)
api=Api(websocket_blue)
conndict={}
userlist=[]

@websocket_blue.route("/WebSockets")
class WebSockets(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self,origin):
        return True
    # 建立连接
    def open(self):
        # 获取参数
        id=str(self.get_query_argument("userid"))
        name=str(self.get_query_argument("name"))
        # 存储链接
        conndict[id]=self
        index=id.find("kefu")
        if index>=0:
            # 判断是否是客服 如果是返回userlist
            self.write_message({"code":200,"userlist":userlist,"mes":{}})
        else:
            # 判断是否为用户 如果是加入userlist
            userlist.append({"id":id,"name":name})
            # 用户上线
            key="levelmes"+str(id)
            mm=r.get_str(key)
            if mm:
                mm=mm.decode()
                self.write_message({"code":200,"userlist":userlist,"mes":mm})
    # 接收消息
    def on_message(self,mes):
        mes=json.loads(mes)
        id=str(mes["id"])
        mes=mes["mes"]
        # 如果客服给用户发 判断用户是否在线 如果不在线将消息存入redis key：用户id+"levelmes",value:[]
        if id in conndict:
            conndict[id].write_message({"code":200,"mes":mes,"userlist":userlist})
        else:
            # 存入redis
            key="levelmes"+str(id)
            # 用户不存在 把消息存入redis
            mes=r.add_str(key,mes)
    def on_close(self):
        pass
@websocket_blue.route("/tt")
class TThandler(tornado.web.RequestHandler):
    def get(self):
        msg=self.get_query_argument("mes")
        id=int(self.get_query_argument("id"))
        conndict[id].write_message(msg)
@websocket_blue.route("/gree")
class Greehouse(tornado.web.RequestHandler):
    def get(self):
        id=int(self.get_query_argument("id"))
        while True:
            web=r.get_str("key")
            if web:
                key=int(web.decocde())
                sql="select * from user1"